(function(){
	/**
	 * 自增ID,用于生成全局回调函数名称和script element id
	 */
	var sid = 0;
	
	var history = {};
	
	/**
	 * 发送jsonp请求
	 * @param {String} url 请求url
	 * @param {Function} cb 回调函数
	 */
	function do_jsonp(url, cb){
		var callback 	= '_do_json' + sid,
			scriptid 	= '_do_json_scr' + sid,
			head 		= document.getElementsByTagName('head')[0],
			script		= document.createElement('script');
		script.id = scriptid;
		history[callback] = true;
		window[callback] = function(){
			if (history[callback]){
				//调用回调函数
				cb.apply(cb, arguments);				
			}
			history[callback] = null;
			//防止内存泄露 参见 http://neil.fraser.name/news/2009/07/27/
			script.parentNode.removeChild(script);
			for (var prop in script){
				try {
					script[prop] = null;
					delete script[prop];
				}catch(e){}
			}
			window[callback] = function(){};
		};		
		++sid;
		if (/\{cb\}/i.test(url)){
			//替换callback名称
			url.replace(/\{cb\}/i, callback)
		}
		else{
			url += ((url.indexOf('?') != -1) ? '&' : '?') + 'callback=' + callback;
		}
		script.src = url;
		script.type = 'text/javascript';
		head.appendChild(script);
	}

	/**
	 * 封装yql请求
	 * @param {Object} reqUrl 需要YQL抓取的网页
	 * @param {Object} cb 回调函数
	 * @param {Object} options 选项
	 *  {
	 *  	format : string[json|xml],
	 *  	xpath  : string XPATH表达式
	 *  }
	 */
	function yql_request(reqUrl, cb, options){
		options = (typeof options == 'object') ? options : {};
		//默认格式JSON
		options.format = options.format ? options.format : 'json';
		var query = ['select * from html where url="' , reqUrl , '"'].join('');
		if (options.xpath){
			query += ' and xpath="' + options.xpath + '"';
		}
		var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=' + options.format;
		do_jsonp(url, cb)
	}
	
	/**
	 * 发送yql请求,返回数据将xml转化为json
	 * @param {Object} reqUrl
	 * @param {Object} xpath
	 * @param {Object} cb
	 */
	function yql_req_json(reqUrl, xpath, cb){
		if(typeof xpath == 'function'){
			cb = xpath;
			xpath = null;
		}
		yql_request(reqUrl, cb, {'xpath':xpath, 'format':'json'});
	}
	
	/**
	 * 发送yql请求,返回数据将xml转化为string
	 * @param {Object} reqUrl
	 * @param {Object} xpath
	 * @param {Object} cb
	 */
	function yql_req_html(reqUrl, xpath, cb){
		if(typeof xpath == 'function'){
			cb = xpath;
			xpath = null;
		}		
		yql_request(reqUrl, cb, {'xpath':xpath, 'format':'xml'});
	}
	
	window.yql_req_json = yql_req_json;
	window.yql_req_html = yql_req_html;
})();
